
#import csv
import matplotlib.pyplot as plt
import numpy as np
#import numpy.matlib
#import datetime
#import time
import PBAR_Zspec
#from mpl_toolkits.mplot3d import Axes3D
import mlpy
from scipy.optimize import curve_fit

reload(PBAR_Zspec)

def gauss_function(x, a, x0, sigma):
    return a*np.exp(-(x-x0)**2/(2*sigma**2))

# Set useful plot variables
plotColors = ['r', 'b', 'g', 'm', 'c', 'y', 'k'] * 10
lineStyles = ['-', '-.', ':', '_', '|'] *  10
markerTypes = ['.', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd']
markerTypes = markerTypes * 2

######################################
##  LOAD DATA AND CALCULATE STATS   ##
######################################

# Set dataset location
basepath = r'C:\Users\jkwong\Documents\Work\PBAR\data'
# Create list of datasets
(filenameList, fullfilenameList) = \
               PBAR_Zspec.GenerateDefaultDatasetFilenameList(basepath)               
# Create list of dataset groups
(datasetGroups, datasetGroupsIndices) = \
                PBAR_Zspec.GenerateDefaultDatasetGroupList(filenameList)
# Create list of good/bad detectors
(goodDetectorsList, badDetectorsList) = \
                    PBAR_Zspec.GenerateDefaultDetectorList()
# Load summary data
infoFilename = basepath + '\\' + 'datasetSummaryOLD.txt'

(datasetDescription, datasetAcquisitionTime, \
    datasetTime, datasetTimeNum, datasetTimeStr) = \
    PBAR_Zspec.GetDatasetInformation(infoFilename, filenameList)

# Load Zspec data
print "Loading Data"
dat = PBAR_Zspec.ReadZspec(fullfilenameList)

# Load Radiography data
(datRad, datRadZspec, radMap) = PBAR_Zspec.ReadRad(basepath)

# Read in the Calibration file
(calTimeNum, calGainShift) = PBAR_Zspec.LoadGainCalibration(basepath + '\\' + 'GainCorrectionVer2.csv')

# Generate extrapolated gain matrix
gainExtrapolated = PBAR_Zspec.ExtrapolateGain(calTimeNum, calGainShift, datasetTimeNum)

# multiple the bin array with this to calibrate
gainCorrection = 100.0/gainExtrapolated

# Calculate the spectra stats
binThreshold = 8

# Pulse rate which has always be 60 Hz
pulseRate = 60 * np.ones(len(dat))

# calculate the stats
stats = PBAR_Zspec.CalculateStats(dat, datasetAcquisitionTime, np.arange(256).astype(float), gainCorrection, basepath, binThreshold, pulseRate)
